import { defineStore } from 'pinia'
import { authAPI } from '@/api/auth'
import router from '@/router'
import { encrypt, decrypt } from '@/utils/crypto'
import { nextTick } from 'vue'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    access_token: null,
    loading: false,
    error: null
  }),

  actions: {
    // 从本地存储初始化用户信息
    initializeFromStorage() {
      try {
        // 解密读取
        const access_token = localStorage.getItem('access_token')
        const user = JSON.parse(decrypt(localStorage.getItem('user')))

        if (access_token && user) {
          this.user = user
          this.access_token = access_token
        }
      } catch (error) {
        this.clearAuth()
      }
    },
    async register(userData) {
      try {
        this.loading = true
        const res = await authAPI.register(userData)
        this.error = null
        return res.data.user_id // 返回新用户ID
      } catch (error) {
        this.handleError(error)
      } finally {
        this.loading = false
      }
    },

    async login(credentials) {
      try {
        this.loading = true
        const { data } = await authAPI.login(credentials)

        // 存储认证信息
        this.$patch((state) => {
          state.user = data.user
          state.access_token = data.access_token
        })
        // 加密存储
        localStorage.setItem('access_token', data.access_token)
        localStorage.setItem('user', encrypt(JSON.stringify(data.user)))

        await nextTick() // 等待Vue的响应式更新
        
        await router.push('/home/main')

        this.error = null

      } catch (error) {
        // 发生错误时回滚状态
        this.user = null
        this.access_token = null
        localStorage.removeItem('access_token')
        localStorage.removeItem('user')
        this.handleError(error)
      } finally {
        this.loading = false
      }
    },

    logout() {
      this.user = null
      this.access_token = null
      localStorage.clear()
      sessionStorage.clear()

      router.push('/login')
    },

    handleError(error) {
      const status = error.response?.status
      const message = error.response?.data?.msg

      switch (status) {
        case 400:
          this.error = message || '请求参数错误'
          break
        case 401:
          this.error = message || '认证失败，请检查凭证'
          break
        case 409:
          this.error = message || '用户已存在'
          break
        default:
          this.error = '服务器连接异常'
      }
    }
  },

  getters: {
    isAuthenticated: state => !!state.access_token
  }
})